package com.topscomm.pm.quartz;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.quartz.JobExecutionContext;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.topscomm.cbo.pojo.CboSysParamEntity;
import com.topscomm.cbo.service.ICboSysParamService;
import com.topscomm.pm.pojo.PmProjectEntity;
import com.topscomm.pm.pojo.PmRecBillEntity;
import com.topscomm.pm.service.IPmProjectService;
import com.topscomm.pm.service.IPmRecBillService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.tap.common.ParameterCache;
import com.topscomm.tap.quartz.TapJob;

/**
 * @author:
 select arline.id,arline.drdocno,arline.createdby,arline.createdon,linehead.docno as ardocno,line.linenum,rlinehead.docno as recdocno,
        line.item_itemcode,line.item_itemname,arline.crapplyfcmoney_totalmoney,
        recbkaccname,rlinehead.recdate,cust.name as cust_name,
    cbo_settlementmethod.code as tlementmethodcode,cbo_department.code as deptcode,org.code  as orgcode,org1.name  as orgname
        from AR_ARApplyLine arline --核销单行
        inner join AR_ARBillLine line on line.id=arline.DRBillLineTag --应收单行
        inner join AR_ARBillHead linehead on linehead.id=line.ARBillHead --应收单
        inner join AR_RecBillLine rline on rline.id=arline.CRBillLineTag --收款单行
        inner join AR_RecBillHead rlineHead on rlineHead.id=rline.RecBillHead --收款单头
      left join CBO_SettlementMethod on CBO_SettlementMethod.id=    rline.SettlementMethod
        left join CBO_Department on CBO_Department.id=rlineHead.dept
        inner join Base_Organization org on org.id=linehead.org
        inner join Base_Organization_trl org1 on org1.id=linehead.org
        inner join CBO_Customer_trl cust on cust.id=rlinehead.cust_customer
        where line.SrcDocType =0 and arline.CreatedOn>='2020-01-01 00:00:00'  --0代表销售订单立账
        and arline.CreatedOn<='2020-07-01 00:00:00'
 * @date: 2020/6/10
 * @description: 自动创建收款单据
 */
@Component
public class PmProjectRecBillJob extends TapJob {

    @Override
    public void run(JobExecutionContext jobExecutionContext){
        JSONObject map = new JSONObject();
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(2000);// 设置超时
        requestFactory.setReadTimeout(10000);//读取超时时间
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        String token = ParameterCache.getValue("DataServiceUrl_Token");
        String templateid = ParameterCache.getValue("ERPServiceUrl_RecID");
        headers.set("token", token);
        ICboSysParamService cboSysParamService = (ICboSysParamService)SpringUtil.getBean("cboSysParamService");
        map.put("templateid", templateid);
        IPmRecBillService pmRecBillService = (IPmRecBillService) SpringUtil.getBean("pmRecBillService");
        IPmProjectService pmProjectService = (IPmProjectService) SpringUtil.getBean("pmProjectService");
        try {
            String url = ParameterCache.getValue("ERPUrl_Query");
            //提前10分钟，防止在更新时间点上造成数据遗漏
            CboSysParamEntity entity =cboSysParamService.queryObjectByWhere("code='PM_ERPARLastSynDate'");
            if(entity==null)
            {
                entity=new CboSysParamEntity();
                entity.setCode("PM_ERPARLastSynDate");
                entity.setName("项目管理获取收款信息最后时间");
                entity.setCategory("Cbo");
                entity.setModule("PM");
                entity.setParamvalue("2020-07-01 01:01:01");
            }
            Date date2 = new Date();
            String createon2 = DateUtil.dateToString(date2);
            JSONObject params = new JSONObject();
            params.put("CreatedOn1", entity.getParamvalue());
            params.put("CreatedOn2", createon2);
            map.put("paramsMap", params);

            int pageNum=1;
            int pageSize=100;
            int totalPage=0;
            map.put("pageNum",pageNum);
            map.put("pageSize", pageSize);

            HttpEntity<JSONObject> request = new HttpEntity<>(map, headers);
            ResponseEntity<JSONObject> response = restTemplate
                .postForEntity(url, request, JSONObject.class);
            if(response.getBody().getBooleanValue("success")==true)
            {
                totalPage=response.getBody().getJSONObject("result").getIntValue("totalPage");
                List<Map<String, Object>> dataList = (List)response.getBody().getJSONObject("result").getJSONArray("dataList");
                doData(dataList,pmRecBillService,pmProjectService);
                //如果只有一页数据
                if(totalPage>1)
                {
                    for(pageNum=2;pageNum<=totalPage;pageNum++)
                    {
                        map.put("pageNum",pageNum);
                        map.put("pageSize", pageSize);
                        request = new HttpEntity<>(map, headers);
                        response = restTemplate
                            .postForEntity(url, request, JSONObject.class);
                        dataList = (List)response.getBody().getJSONObject("result").getJSONArray("dataList");
                        doData(dataList,pmRecBillService,pmProjectService);
                    }
                }
            }
            else
                throw new Exception("获取ERP收款信息错误！");
            createon2 = DateUtil.dateToString(DateUtil.addDate(date2,-10, Calendar.MINUTE));
            entity.setParamvalue(createon2);
            if(entity.getId()>0)
                cboSysParamService.updateEntity(entity);
            else
                cboSysParamService.insert(entity);
        }
        catch(Exception e)
        {
           //throw new Exception("获取ERP收款信息错误！");
        }
    }

    private void doData(List<Map<String, Object>> dataList,IPmRecBillService pmRecBillService,IPmProjectService pmProjectService)
    {
        for(Map row : dataList)
        {
            String projectcode = ConvertUtil.convertToString(row.get("item_itemcode"));
            if(StringUtil.isEmpty(projectcode))continue;//如果没有项目对应，不处理
            PmProjectEntity projectEntity = pmProjectService.queryObjectByWhere("code='"+projectcode+"'");
            if(projectEntity==null)continue;//如果没有项目对应，不处理
            //先删除后插入
            String id = ConvertUtil.convertToString(row.get("id"));
            pmRecBillService.deleteByWhere("erpid="+id);
            PmRecBillEntity ent=new PmRecBillEntity();
            //项目
            ent.setProjectid(projectEntity.getId());
            //客户名称
            ent.setCustomername(ConvertUtil.convertToString(row.get("cust_name")));
            //收款组织
            ent.setRecbillorgcode(ConvertUtil.convertToString(row.get("orgcode")));
            //收款组织名称
            ent.setRecbillorgname(ConvertUtil.convertToString(row.get("orgname")));
            //收款金额
            ent.setMoney(ConvertUtil.convertToBigDecimal(row.get("crapplyfcmoney_totalmoney")));
            //收款时间
            ent.setRecdate(ConvertUtil.convertToDate(row.get("recdate")));
            //收款方式
            ent.setCollectionmethod(ConvertUtil.convertToString(row.get("tlementmethodcode")));
            //收款单号
            ent.setRecbillno(ConvertUtil.convertToString(row.get("recdocno")));
            //收款账户
            ent.setCollectionaccount(ConvertUtil.convertToString(row.get("recbkaccname")));
            //单据状态
            ent.setState(9);
            ent.setErpid(ConvertUtil.convertToLong(id));
            //单据日期 和收款日期等同
            ent.setDocdate(ent.getRecdate());;

            //备注
            ent.setDescription("来自ERP，核销人为："+ConvertUtil.convertToString(row.get("createdby"))+";"
                    +"应收单号为："+ConvertUtil.convertToString(row.get("ardocno"))+";"
                    );
            pmRecBillService.insert(ent);
        }
    }
}
